﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using Newtonsoft.Json;

namespace Pay.ApplePay
{
    public class ApplePayContext
    {
        private static string certificateUrl = "https://buy.itunes.apple.com/verifyReceipt";
        private static string certificateUrlTest = "https://sandbox.itunes.apple.com/verifyReceipt";
        /// <summary>
        /// 苹果内购验证
        /// </summary>
        /// <param name="param"></param>
        /// <param name="istest"></param>
        public static void Verify(string param)
        {
            try
            {
                //是否内购测试
                var apple_pay_test = WebConfigurationManager.AppSettings["apple_pay_test"];
                var url = apple_pay_test == Boolean.TrueString ? certificateUrlTest : certificateUrl;
                var transaction = JsonConvert.DeserializeObject<dynamic>(param);
                var transactionReceipt = (string)transaction.transactionReceipt;
                //byte[] array = Encoding.UTF8.GetBytes(transactionReceipt);
                //var base64String = Convert.ToBase64String(array);
                var data = "{\"receipt-data\":\"" + transactionReceipt + "\"}";
                var result = WebClient.Post(url, data).Content.ReadAsStringAsync().Result;
                var res = JsonConvert.DeserializeObject<dynamic>(result);
                int status = (int)res.status;
                if (status != 0)
                {
                    throw new Exception(string.Format("内购验证失败，代码：{0}", status));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("内购验证失败，错误：{0}", ex.Message));
            }
        }
    }
}
